import Singleton from "../context/Singleton";

/**资源管理 */
export default class ResManage extends Singleton {

    public static get I() { return this.Instance() }

    private $assets = new Map<string, ResData>();

    private $assetKey = "_RESOURCES_";


    public gc() {
        Laya.Resource.destroyUnusedResources();
    }


    load(url: string) {

    }

    /**
     * 异步获取资源
     * @param url 路径
     * @param type 类型
     */
    getRes(url: string, type?: string): Promise<any> {
        return new Promise<any>(function (resolve) {
            let loader = Laya.loader;
            let res = loader.getRes(url);
            if (res)
                resolve(res);
            else
                loader.load(url, Laya.Handler.create(null, resolve), null, type);
        })
    }

    getByGroup(g: string) {
        if (!this.$assets.has(g)) {
            let obj = Laya.Pool.getItemByClass(this.$assetKey, ResData);
            obj.group = g;
            this.$assets.set(g, obj);
        }

        return this.$assets.get(g);
    }

    clearRes(group: string) {
        let asset = this.$assets.get(group)
        if (!asset) return;
        asset.clera();
        this.$assets.delete(group);
        Laya.Pool.recover(this.$assetKey, asset);
    }


}


class ResData {

    private group: string;
    private assets: Partial<loadItem>[];

    constructor() {
        this.assets = [];
    }

    add(url: Partial<loadItem> | Partial<loadItem>[]) {
        if (url instanceof Array) {
            for (let item of url) {
                this.pushAss(item);
            }
        } else {
            this.pushAss(url);
        }

    }

    load() {
        return this.loadAsset(this.assets, 3);
    }

    loadImg(obj: Laya.Sprite, url: string) {
        this.pushAss({ url: url, type: Laya.Loader.IMAGE });
        if (obj != null) {
            obj.loadImage(url);
        }
    }

    loadJson(url: string) {
        let asset = { url: url, type: Laya.Loader.JSON }
        this.assets.push(asset);
        this.loadAsset(url);
    }

    clera() {
        if (this.assets.length <= 0) return;

        // for (let item of this.assets) {
        //     Laya.loader.clearRes(item.url);
        // }

        Laya.Loader.clearResByGroup(this.group);

        this.assets.length = 0;
    }

    loadAsset(url: any, priority = 1, progress?: Laya.Handler) {
        return new Promise<void>((resolve, regect) => {

            Laya.loader.load(url, Laya.Handler.create(this, () => resolve())
                , progress, null, priority, true, this.group, false);
        })
    }

    private pushAss(c: any) {
        let b = this.assets.some(v => v.url == c.url);
        if (b) return;
        this.assets.push(c);
    }
}


interface loadItem {
    url: string;
    type: string;
    size: number;
    priority: number;
    useWorkerLoader: boolean;
    progress: number;
    group: string;
}